#include "login.h"

//发送方
#define send_piv "192.168.0.176"
#define send_port 7777
//接收方
#define get_piv "192.168.0.194"
#define get_port 6666

//服务端返回suc值判断为成功登录
#define suc "0"
/*
typedef struct{
	char order[20];
	char name[20];
	char pas[20];
}TRAN;
*/
char buff[1024];
int client_login(int sel)//客户端登录/注册函数
{
	//创建TCP类型套接字
	int client_socket=socket(AF_INET,SOCK_STREAM,0);
	
	//向服务端发起连接请求
	struct sockaddr_in saddr;
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(get_port);   //port 
	saddr.sin_addr.s_addr = inet_addr(get_piv);   //ip
	int isok = connect(client_socket,(struct sockaddr*)&saddr,sizeof(saddr));
	if(isok == -1)
	{
		perror("connect");	
		return -1;
	}
	printf("已成功与服务器建立连接\n");
	
	//登录
	TRAN node;
	bzero(&node,sizeof(node));
	printf("已进入登录界面\n");
	printf("请输入用户名:");
	scanf("%s",node.name);
	printf("请输入用户密码:");
	scanf("%s",node.pas);
	//向服务端发送登录/注册请求
	if(sel==1)
		strcpy(node.order,"login");
	else if(sel==2)
		strcpy(node.order,"register");
		
	packJson(&node);

	printf("准备向服务端发送信息:%s\n",buff);
	write(client_socket,buff,strlen(buff));
	
	
	//将文件描述符改为非阻塞状态便于read使用
	int flags, s;
	// 获取当前的文件状态标志
	flags = fcntl(client_socket,F_GETFL,0);
	if (flags == -1) {
		perror("fcntl F_GETFL");
		return -1;
	}
	// 添加O_NONBLOCK标志
	flags |= O_NONBLOCK;
	// 设置新的文件状态标志
	s = fcntl(client_socket,F_SETFL,flags);
	if (s == -1) {
		perror("fcntl F_SETFL");
		return -1;
	}
	
	
	puts("准备从服务器接收返回值");
	bzero(buff,sizeof(buff));
	sleep(2);
	int num=read(client_socket,buff,1024);
	if(num<=0){
		puts("已超时,未能接收到返回值");
		return -1;
	}
	else
		printf("接收到返回值:%s\n",buff);
	printf("客户端退出\n");	
	close(client_socket);
	if(strcmp(suc,buff)==0)
		return 0;
	else
		return -1;
}
void packJson(TRAN *head)
{
	cJSON* root = cJSON_CreateObject();
	cJSON* order = cJSON_CreateString(head->order);
	cJSON* name = cJSON_CreateString(head->name);
	cJSON* pas = cJSON_CreateString(head->pas);

	cJSON_AddItemToObject(root,"order",order);
	cJSON_AddItemToObject(root,"name",name);
	cJSON_AddItemToObject(root,"pwd",pas);
	
	char *p=buff;
	p=cJSON_Print(root);
	strcpy(buff,p);
	cJSON_Delete(root);
}
